package com.example.demo.service;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class SocketVerify {
    /**
     * 用字符流读取数据
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static String readData(InputStream in) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String msg = br.readLine();
        return msg;
    }
    public static void main(String[] args) throws IOException {
// 名字
        String stringName = "小李";
        String pwd = "123456";
        // 通信
        ServerSocket serverSocket = new ServerSocket();
        // 端口号
        SocketAddress address = new InetSocketAddress(8080);
        // 设置通信的端口号 bind(SocketAddress endpoint)
        // 将 ServerSocket 绑定到特定地址（IP 地址和端口号）。
        serverSocket.bind(address);
        // accept()侦听并接受到此套接字的连接。
        System.out.println("服务器启动");
        while (true) {
            Socket socket = serverSocket.accept();
            //获取客户端的值
            String msg = readData(socket.getInputStream());
            //返回客户端
            OutputStream out = socket.getOutputStream();
            //分割
            String[] strmsg = msg.split(",");
            System.out.println("分割后的数据"+strmsg[0] + strmsg[1]);
            if (strmsg[0].equals(stringName) && strmsg[1].equals(pwd)) {
                // OutputStreamWriter writer = new OutputStreamWriter(out2);
                // writer.write("111");
                //成功返回1
                out.write(1);
            } else {
                //失败-1
                out.write(-1);
            }
            socket.close();
        }

    }
}
